from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
import time,os
from shop.settings import BASE_DIR
from django.core.paginator import Paginator
from django.db.models import Q
from django.contrib.auth.decorators import permission_required

#订单相关
def orderlist(request):
    uid = request.session['userinfo']['uid']
    uorderss = models.Order.objects.filter(uid=uid)
    goods = models.Goods.objects.all().values()



    #     # 实例化分页对象
    p = Paginator(uorderss, 2)

    #一共可以分多少页
    sumpage=p.num_pages
# num_pages

    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据
    page1 = p.page(page)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]




    return render(request,'myadmin/order/orderlist.html',{'goods':goods,'uorderss':page1,'prange':prange})



#修改
def orderedit(request):
    #接收用户id
    uid = request.GET.get('uid')
    #判断传输类型，如果是get 直接跳转到修页面
    
    if request.method=="GET":
        uorder = models.Order.objects.all().values()
        uor = models.Order.objects.get(id=uid)
        return render(request,'myadmin/order/orderedit.html',{'uorder':uorder,'uor':uor})

    elif request.method=='POST':
        uorder = models.Order.objects.get(id=uid)
        #获取提交的数据并转化为字典
        orders = request.POST.dict()
        #获取当前的数据
        
        #更新数据
        uorder.total =orders['price']
        uorder.save()
       
        return HttpResponse("<script>alert('修改成功');location.href='/myadmin/orderlist/'</script>")






#删除
def orderdel(request):
    uid = request.GET.get('uid')
    user = models.Order.objects.get(id=uid)
    user.delete()
    return redirect(reverse('myadmin_orderlist'))